package com.aramis.mydytt.ui.topic

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aramis.mydytt.R
import com.aramis.mydytt.ui.base.BaseFragment
import com.aramis.mydytt.ui.topic.detail.TopicDetailActivity
import com.aramis.mydytt.widget.LoadingStateView

/**
 * Description: MainTopicFragment
 * 专题Fragment
 * @author lizhidan
 * Created: 2021/4/6
 */
class MainTopicFragment : BaseFragment() {
    private lateinit var mainTopicViewModel: MainTopicViewModel
    private val listAdapter = MainTopicListAdapter()
    private var currentPage = 1
    private var loadingView: LoadingStateView? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mainTopicViewModel = createViewModel()
        val view = inflater.inflate(R.layout.fragment_main_topic, container, false)
        initView(view)
        initData()
        return view
    }

    private fun initData() {
        mainTopicViewModel.topicListData.observe(viewLifecycleOwner, {
            loadingView?.showState(it)
            if (currentPage == 1) {
                listAdapter.setData(it)
            } else {
                listAdapter.addData(it)
            }
            if (it != null && it.isNotEmpty()) {
                currentPage++
            }
        })
        requestData()
    }

    private fun requestData() {
        mainTopicViewModel.getSearchResult(currentPage)
    }

    private fun initView(root: View) {
        val recyclerView = root.findViewById<RecyclerView>(R.id.list_topic)
        recyclerView.adapter = listAdapter
        recyclerView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        listAdapter.onItemClickListener = {
            val intent = Intent(activity, TopicDetailActivity::class.java)
            intent.putExtra("data", it)
            startActivity(intent)
        }
        loadingView = root.findViewById(R.id.view_loading)
        loadingView?.setOnErrorRetryListener { requestData() }
    }
}